#include "compensate_data_dialog.h"

#include <QCloseEvent>
#include <QMessageBox>

#include "ui_compensate_data_dialog.h"

CompensateDataDialog::CompensateDataDialog(
    std::shared_ptr<lidar_imu_calibrator::OdometryFrameSet> odometry_frame_set,
    QWidget *parent)
    : QDialog(parent),
      ui(new Ui::CompensateDataDialog),
      odometry_frame_set_(odometry_frame_set),
      start_flag_(false) {
  ui->setupUi(this);
  this->setFixedSize(this->size());
  ui->progressBar->setMinimum(0);
  ui->progressBar->setMaximum(100);
  ui->progressBar->setValue(0);
  connect(odometry_frame_set_.get(),
          &lidar_imu_calibrator::OdometryFrameSet::ProgressChanged, this,
          &CompensateDataDialog::ProgressChanged);
  Start();
}

CompensateDataDialog::~CompensateDataDialog() { delete ui; }

void CompensateDataDialog::closeEvent(QCloseEvent *event) {
  if (start_flag_) {
    if (QMessageBox::question(
            this, QStringLiteral("Prompt"),
            QStringLiteral(
                "Are you sure you want to exit the compensate data?"),
            QMessageBox::Yes | QMessageBox::No,
            QMessageBox::No) == QMessageBox::No) {
      event->ignore();
      return;
    }
    Stop();
  }
  event->accept();
}

void CompensateDataDialog::on_btnStart_clicked() {
  if (start_flag_) {
    if (QMessageBox::question(
            this, QStringLiteral("Prompt"),
            QStringLiteral(
                "Are you sure you want to stop the compensate data?"),
            QMessageBox::Yes | QMessageBox::No,
            QMessageBox::No) == QMessageBox::Yes) {
      Stop();
    }
  } else {
    Start();
  }
}

void CompensateDataDialog::on_btnCancel_clicked() { close(); }

void CompensateDataDialog::ProgressChanged(int percent) {
  if (this->ui->progressBar->value() != percent) {
    this->ui->progressBar->setValue(percent);
    if (percent == 100) {
      Stop();
      accept();
    }
  }
}

void CompensateDataDialog::Start() {
  odometry_frame_set_->StartCompensateData();
  this->ui->btnStart->setText("Stop");
  start_flag_ = true;
}

void CompensateDataDialog::Stop() {
  odometry_frame_set_->Stop();
  this->ui->btnStart->setText("Start");
  start_flag_ = false;
}